package com.edu.service;

import com.edu.pojo.NormalKeys;
import com.edu.pojo.User;
import com.edu.util.JedisPoolUtil;
import com.edu.util.JsonUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author five-five
 * @created 2021/11/26-16:39
 */
public class UserService {
    /**
     * 去redis中查询
     *
     * @param user
     * @return
     */
    public boolean getUserByUserNameAndPwd(User user) {
        boolean flag = false;
        JedisPoolUtil.getJedisPoolInstance();
        String userlist = JedisPoolUtil.get(NormalKeys.USERLIST);
        List<User> users = null;
        if (userlist == null) {
            users = new ArrayList<>();
        } else {
            users = JsonUtil.jsonToList(userlist, User.class);
        }
        if (users == null) {
            return flag;
        }
        for (User cur : users) {
            if (user.getName().equals(cur.getName()) && user.getPassword().equals(cur.getPassword())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 创建用户
     *
     * @param user
     * @return
     */
    public boolean addUserByUserNameAndPwd(User user) {
        try {
            JedisPoolUtil.getJedisPoolInstance();
            String userlist = JedisPoolUtil.get(NormalKeys.USERLIST);
            List<User> users = null;
            if (userlist == null) {
                users = new ArrayList<>();
                users.add(user);
                JedisPoolUtil.set(NormalKeys.USERLIST, JsonUtil.objectToJson(users));
                return true;
            }
            users = JsonUtil.jsonToList(userlist, User.class);
            for (User u : users) {
                if (u.getName().equals(user.getName())) {
                    System.out.println("===================用户名相同，请重新输入===================");
                    return false;
                }
            }
            users.add(user);
            JedisPoolUtil.set(NormalKeys.USERLIST, JsonUtil.objectToJson(users));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
